<template>
  <div>
    <el-dialog
      title="选择角色"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="false"
      width="30%"
    >
      <el-radio-group v-model="rolescode" class="rolesgroup" @change="change">
        <el-radio
          v-for="t in roles"
          :key="t.shipercode"
          style="margin: 5px"
          border
          :label="t.shipercode"
        >
          {{ t.shipername }}
        </el-radio>
        <!-- SHIPERNAME -->
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          @click="queryRoles"
        >确 定</el-button>
        <el-button @click="cancelRoles">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserInfo } from "@/utils/auth";
import { mapState } from "vuex";
export default {
  name: "TabRoles",
  data() {
    return {
      dialogVisible: false,
      rolescode: getUserInfo().rolescode,
      redirect: "",
      loading: false,
    };
  },
  computed: {
    ...mapState("user", ["roles", "routers"]),
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  methods: {
    change(e) {
      // console.log(e);
      this.$emit("change", e);
    },
    opentabroles() {
      if (this.roles.length === 1) {
        if (this.$route.name === "login") {
          this.rolescode = this.roles[0].shipercode;
          this.queryRoles();
        } else {
          this.$message({ type: "warning", message: "您当前的角色仅此一个" });
        }
      } else {
        this.dialogVisible = true;
      }
    },
    async queryRoles() {
      if (this.rolescode) {
        const ojb = {
          rolescode: this.rolescode,
        };
        this.loading = true;
        // 切换角色
        await this.$store.dispatch("user/tabRoles", ojb);
        if (this.$route.name !== "login") {
          // 如果不是登录接口
          await this.$store.dispatch("user/getInfo");
          // this.$router.push({ path: "/" });
          // location.reload();
        }
        // 清除tab标签
        this.$store.dispatch("tagsView/delAllVisitedViews");
        this.$router.push({ path: "/" });
        this.loading = false;
        // 关闭弹窗
        this.dialogVisible = false;
        // this.redirect ||
      } else {
        this.$message({
          message: "请选择一个角色",
          type: "warning",
        });
      }
    },
    cancelRoles() {
      this.dialogVisible = false;
      this.$emit("cancelRoles", false);
    },
  },
};
</script>

<style scoped lang="scss">
.rolesgroup {
  display: flex;
  flex-direction: column;
}
</style>
